package view.listener;

import java.util.List;

import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import singleton.Singleton;
import view.views.CSADView;
import controller.UseCaseController;

public class EditListener implements Listener {

	private final CSADView view;
	private final UseCaseController useCaseController;
	private final String id;
	private final int i;

	public EditListener(String id, CSADView view,
			UseCaseController useCaseController, int i) {
		this.id = id;
		this.view = view;
		this.useCaseController = useCaseController;
		this.i = i;
	}

	public void handleEvent(Event event) {
		if (view.searchString.length() != 0) {
			if (i == -1) {
				view.newDoc = true;
				Singleton.getInstance().setDocumentText(
						view.searchString
								+ " ("
								+ Singleton.getInstance().getActualTab()
										.getTabItemName() + ")");
				Singleton.getInstance().setTitle("");
				Singleton.getInstance().setText("");
				Singleton.getInstance().setTags("");
			} else {
				view.newDoc = false;
				Singleton.getInstance().setDocumentText(
						view.searchString
								+ " - "
								+ view.listOfData
										.get(Singleton.getInstance()
												.getPosition()).getRevision()
										.getHeader()
								+ " ("
								+ Singleton.getInstance().getActualTab()
										.getTabItemName() + ")");
				Singleton.getInstance().setTitle(
						view.listOfData.get(i).getRevision().getHeader());
				Singleton.getInstance().setText(
						view.listOfData.get(i).getRevision().getContent());
				// Activator.setTags(view.listOfData.get(i).);
				String tag = getTags(view.listOfData.get(i).getTags());
				Singleton.getInstance().setTags(tag);
			}
			useCaseController.setId(id);
			view.setEditorDoc(view.openEditor(view.getEditorDoc(), "muster.min"));
		}
	}

	private String getTags(List<String> tags) {
		StringBuilder tmp = new StringBuilder();
		for(int i = 0; i < tags.size(); i++){
			tmp.append(tags.get(i));
			tmp.append(";");
		}
		return tmp.toString();
	}
}